<?php
namespace app\admin\controller;


class Plugin extends Base
{
  public function pluginList()
  {
    $pluginList =  getAddonList();
    return view("/plugin",["pluginList" => $pluginList]);
  }



  // 插件安装
  public function install()
  {
    $name = input("name");
    $class = get_addon_class($name);
    $result = (new $class)->install();
    if($result === true){
      return json(["code" => 1 ,"msg" => "安装成功"]);
    }
    return json(["code" => 0 ,"msg" => "安装失败"]);
  }

  //插件卸载
  public function uninstall()
  {
    $name = input("name");
    $class=get_addon_class($name);
    $result=(new $class)->uninstall();
    if($result === true){
      return json(["code" => 1 ,"msg" => "卸载成功"]);
    }
    return json(["code" => 0 ,"msg" => "卸载失败"]);
  }
  //插件启用
  public function open()
  {
    $name = input("name");
    $config = ["name" => $name,"status" => 2];
    $result=create_config($config);
    if($result){
      return json(["code" => 1,"msg" => "启用成功"]);
    }
    return json(["code" => 0,"msg" => "启用失败"]);
  }
  //插件关闭
  public function stop()
  {
    $name = input("name");
    $config = ["name" => $name,"status" => 1];
    $result=create_config($config);
    if($result){
      return json(["code" => 1,"msg" => "停用成功"]);
    }
    return json(["code" => 0,"msg" => "停用失败"]);
  }
  //插件删除
  public function delete()
  {
    $name = input("name");
    $path = ROOT_PATH ."addons" .DS .$name;
    if(!file_exists($path)){
      return json(["msg" => "该插件不存在"]);
    }    
    if($this->delDirAndFile($path)){
      return json(["code" => 1,"msg" => "已成功删除插件"]);
    }
    return json(["code" => 0,"msg" => "删除插件失败"]);
  }
  //循环删除目录和文件函数 
  function delDirAndFile( $dirName ) 
  { 
    if ( $handle = opendir( "$dirName" ) ) { 
      while ( false !== ( $item = readdir( $handle ) ) ) { 
        if ( $item != "." && $item != "..") { 
          if ( is_dir( "$dirName/$item" ) ) { 
            delDirAndFile("$dirName/$item"); 
          } else { 
            unlink("$dirName/$item"); 
          } 
        } 
      } 
      closedir( $handle ); 
      if( rmdir( $dirName ) ){
        return true;
      } 
      return false;
    } 
  } 
}
